<template>
  <div class="full flex_column_between relative p_10" :class="{chart_box_bgi_1 : isFullscreen}" ref="tree_box">
    <!-- 全屏 -->
    <div class="w_25 h_25 absolute top_10 right_10">
      <img 
        class="full cursor" 
        v-if="isFullscreen" 
        src="~@/assets/images/chart-box/qu-xiao-quan-ping.png" 
        alt="" 
        @click="fullScreen(false)"
      >
      <img class="full cursor" v-if="!isFullscreen" src="~@/assets/images/chart-box/quan-ping.png" alt="" @click="fullScreen(true)">
    </div>

    <div class="h_30 lh_30 main_color fw_bold fs_16 mb_10 ls_2 flex_row_start flex_center">
      <div class="w_1 h_15 main_bgc mr_10"></div>谱系档案
    </div>
    <!-- <div class="color_fff" @click="clearCanvas">清除 canvas</div> -->
    <div id="mountNode1" class="w_full h_full-40 chart_box_bgi_1 border_none" ref="box1" v-show="!isFullscreen"></div>
    <div id="mountNode2" class="w_full h_full-40 chart_box_bgi_1 border_none" ref="box2" v-show="isFullscreen"></div>
  </div>
</template>

<script>
  import screenfull from 'screenfull'
  import G6 from '@antv/g6';

  export default {
    name: 'SheepTree',
    props: {
      chartData: {}
    },
    data() {
      return {
        box1: null,
        box1_width: null,
        box1_height: null,
        isFullscreen: false,
        graph: null,
      }
    },
    watch: {
      chartData: {
        handler(val) {
          console.log('谱系数据 : ', val);
          if (this.graph && val.nodes.length) {
            this.graph.changeData(val)
            this.graph.fitView(10, { onlyOutOfViewPort: true, direction: 'both', ratioRule: 'min' }, true)
          }
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        let box1 = this.$refs.box1
        this.box1_width = box1.offsetWidth
        this.box1_height = box1.offsetHeight
        this.initGraph('mountNode1', box1.offsetWidth, box1.offsetHeight, {})
      })
    },
    methods: {
      initGraph(container, width, height, val) {
        G6.registerNode('rect-jsx',
          (cfg) => `
            <group>
              <rect style={{ cursor: 'pointer' }}>
                <rect style={{
                  width: 150,
                  height: 20,
                  fill: ${cfg.color},
                  radius: [6, 6, 0, 0],
                  cursor: 'pointer'
                  stroke: ${cfg.color}
                }} draggable="true">
                  <text style={{
                    marginTop: 2,
                    marginLeft: 75,
                    textAlign: 'center',
                    fontWeight: 'bold',
                    fill: '#fff' }}>{{disc}}</text>
                </rect>
                <rect style={{
                  width: 150,
                  height: 55,
                  stroke: ${cfg.color},
                  fill: #ffffff,
                  radius: [0, 0, 6, 6],
                }}>
                  <text style={{ marginTop: 10, marginLeft: 3, fill: '#333', marginLeft: 4, fontSize: 18, cursor: 'pointer' }}>羊编号: {{props.cattleId}}</text>
                  <text style={{ marginTop: 20, marginLeft: 3, fill: '#333', marginLeft: 4, fontSize: 18, cursor: 'pointer' }}>性别: {{sex}}</text>
                </rect>
              </rect>

            </group>`,
            // <circle style={{
            //     stroke: ${cfg.color},
            //     r: 20,
            //     marginTop: -30, marginLeft: 130, 
            //     fill: '#fff',
            //     border: 'none',
            //     cursor: 'pointer'
            //   }} name="circle">
            //     <image style={{ img: 'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png', cursor: 'pointer', width: 40, height: 40, marginTop: -15, marginLeft: 110 }} />
            //   </circle>
        );
        
        
        this.graph = new G6.Graph({
          container,
          width,
          height,
          fitView: true,
          fitCenter: true,
          fitViewPadding: 40,
          defaultNode: {
            type: 'card-node',
            size: [200, 50],
            anchorPoints: [
              [0, 0.5],
              [1, 0.5],
            ],
            labelCfg: {
              position: 'bottom',
              style: {
                fill: '#fff',
                fontSize: 14,
              },
              offset: 30,
            },
            style: {
              radius: 5,
              stroke: '#69c0ff',
              fill: '#ffffff',
              lineWidth: 1,
              fillOpacity: 1,
            },
            // 其他配置
          },
          defaultEdge: {
            type: 'cubic-horizontal',
            style: {
              // stroke: '#F6BD16',
            },
          },
          // 定义布局
          layout: {
            width,
            height,
            // random force circular radial mds fruchterman dagre concentric grid dendrogram compactBox mindmap indented 
            type: 'dagre',
            rankdir: 'LR',
            begin: [-500, -300],
            align: '',
            nodesep: 15,
            ranksep: 40
          },
          modes: {
            default: [
              'drag-canvas', 
              'zoom-canvas', 
              'drag-node',
              {
                // 定义展开/收缩行为
                type: 'collapse-expand',
              },
              // {
              //   type: 'tooltip',
              //   formatText(model) {
              //     let text = '耳标: ' + model.id;
              //     return text
              //   }
              // },
              {
                type: 'edge-tooltip', // 边提示框
                formatText(model) {
                  // 边提示框文本内容
                  const text =
                    'source: ' +
                    model.source +
                    '<br/> target: ' +
                    model.target +
                    '<br/> weight: ' +
                    model.weight;
                  return text;
                },
              },
            ]
          },
          nodeStateStyles: {
            hover: {
              fill: 'lightsteelblue',
            },
            click: {
              stroke: '#f00',
              lineWidth: 2
            }
          },
          edgeStateStyles: {
            click: {
              stroke: 'steelblue'
            }
          }
        });

        this.graph.on('node:mouseenter', (e) => {
          let nodeItem = e.item; // 获取鼠标进入的节点元素对象
          this.graph.setItemState(nodeItem, 'hover', true); // 设置当前节点的 hover 状态为 true
        });

        // 鼠标离开节点
        this.graph.on('node:mouseleave', (e) => {
          let nodeItem = e.item; // 获取鼠标离开的节点元素对象
          this.graph.setItemState(nodeItem, 'hover', false); // 设置当前节点的 hover 状态为 false
        });

        // 点击 节点
        this.graph.on('node:click', e => {
          let clickNodes = this.graph.findAllByState('node', 'click');
          clickNodes.forEach((cn) => {
            this.graph.setItemState(cn, 'click', false);
          });

          let nodeItem = e.item; // 获取被点击的节点元素对象
          console.log('点击 : ', nodeItem._cfg.model.props);
          // debugger
          this.graph.setItemState(nodeItem, 'click', true); // 设置当前节点的 click 状态为 true

          let params = {
            cattleId: nodeItem._cfg.model.props.cattleId,
            rfid: nodeItem._cfg.model.props.rfid,
          }
          this.$emit('clickSheep', params)
         
          // this.$router.push(`/sheepRelation/${nodeItem._cfg.model.props.cattleId}/${nodeItem._cfg.model.props.rfid}`)
          
        })

        // 点击 线条
        this.graph.on('edge:click', (e) => {
          // 先将所有当前是 click 状态的边置为非 click 状态
          let clickEdges = this.graph.findAllByState('edge', 'click');
          clickEdges.forEach((ce) => {
            this.graph.setItemState(ce, 'click', false);
          });
          let edgeItem = e.item; // 获取被点击的边元素对象
          this.graph.setItemState(edgeItem, 'click', true); // 设置当前边的 click 状态为 true
        });
        
        this.graph.changeData(val);   // 更新数据
        this.graph.render();   // 渲染图
      },

      clearCanvas() {
        // this.graph.clear()
        this.graph.destroy();
      },

      // 全屏
      fullScreen(val) {
        let element = this.$refs.tree_box

        // 如果不允许进入全屏，发出不允许提示 浏览器不能全屏
       if (!screenfull.isEnabled) {
          this.$message({
            message:'浏览器不能全屏，安装其他版本试试',
            type:'warning'
          })

          return false
        }
        
        this.isFullscreen = val
        
        screenfull.request(element)

        screenfull.toggle()

        this.graph.destroy()

        if (!val) {
          this.initGraph('mountNode1', this.box1_width, this.box1_height, this.chartData)
          this.graph.fitView(10, { onlyOutOfViewPort: true, direction: 'both', ratioRule: 'min' }, true)
        } else {
          let screen_width = document.body.scrollWidth - 40
          let screen_height = document.body.scrollHeight - 40
          this.initGraph('mountNode2', screen_width, screen_height, this.chartData)
        }
      },
    }
  }
</script>

<style>
  /* 提示框的样式 */
  .g6-tooltip {
    border: 1px solid #e2e2e2;
    border-radius: 4px;
    font-size: 12px;
    color: #545454;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 10px 8px;
    box-shadow: rgb(174, 174, 174) 0px 0px 10px;
  }
  .s { color: #f07c7c; }
</style>